/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MessagePane.java
 *
 * Created on 25.08.2011, 5:55:48
 */
package com.tsystems.school.simpleclient;

import java.awt.Color;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTree;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;


/**
 *
 * @author 123
 */
public class MessagePane extends javax.swing.JPanel {
    private String filePath = "D:\\smth\\";
    private Contact contact;
    private String me = "me";
    private String logPath;
    private HistoryWriter hwr;
    /** Creates new form MessagePane */
    public MessagePane() {
        initComponents();
    }
    
    public MessagePane( Contact contact) {
        this();
        this.contact = contact;
        logPath = filePath + contact.getLogin() + ".txt";
        hwr = new HistoryWriter(logPath);
        
    }

    void clearTyping() {
        typingPane.setText("");
    }
class HistoryWriter {

        private String path;
        private PrintWriter output;
        public HistoryWriter(String path) {
            this.path = path;
            try {
                output = new PrintWriter(new FileWriter(path, true));
            } catch (IOException ex) {
                Logger.getLogger(MessageBox.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
        public void writeMessage(String sender, String msg, Date date) {
            String user = sender + " [" + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + "]" + ": \n";
            if (output == null) {
                    try {
                        output = new PrintWriter(new FileWriter(path, true));
                    } catch (IOException ex) {
                        Logger.getLogger(MessageBox.class.getName()).log(Level.SEVERE, null, ex);
                    }
            } 
            output.println(user);
            output.println(msg);
        }
        
        public void endWriting() {
            if (output != null) 
                output.close();
        }
    }
     public Contact getContact() {
         return contact;
     }
     
     public String getTextForSending() {
        return typingPane.getText();
     }
     
     public void writeToHistory(String sender, String str,Date date) {
         hwr.writeMessage(sender, str, date);
     }
     
         public void addMessagePane(String sender, String str, Color clr, Date date) {
        //messagePane.setText(messagePane.getText() + str);
        contact.setMessageFlag(true);
             String user = sender + " [" + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + "]" + ": \n";
        StyledDocument doc = messagePane.getStyledDocument();
        Style style = messagePane.addStyle("Blue", null);
        StyleConstants.setForeground(style, Color.blue);
        try {
            StyleContext sc = StyleContext.getDefaultStyleContext();
            AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY,
                    StyleConstants.Foreground, clr);
            doc.insertString(doc.getLength(), user, aset);
            aset = sc.addAttribute(SimpleAttributeSet.EMPTY,
                    StyleConstants.Foreground, Color.DARK_GRAY);
            doc.insertString(doc.getLength(), str + "\n", aset);
            messagePane.setCaretPosition(doc.getLength());
        } catch (BadLocationException e) {
            // TODO
        }
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane3 = new javax.swing.JScrollPane();
        messagePane = new javax.swing.JTextPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        typingPane = new javax.swing.JTextPane();
        historyButton = new javax.swing.JButton();

        addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                formMouseMoved(evt);
            }
        });

        messagePane.setEditable(false);
        jScrollPane3.setViewportView(messagePane);

        jScrollPane2.setViewportView(typingPane);

        historyButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/tsystems/school/simpleclient/history.gif"))); // NOI18N
        historyButton.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        historyButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                historyButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(historyButton)
                        .addContainerGap(371, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 188, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(historyButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void historyButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_historyButtonActionPerformed
        System.out.println("pressed");
        hwr.endWriting();
        
        HistoryForm hf  = new HistoryForm(logPath, contact.getLogin());
        hf.setVisible(true);
}//GEN-LAST:event_historyButtonActionPerformed

    private void formMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseMoved
        contact.setMessageFlag(false);
        MainForm.getTree().repaint();
    }//GEN-LAST:event_formMouseMoved

    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton historyButton;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextPane messagePane;
    private javax.swing.JTextPane typingPane;
    // End of variables declaration//GEN-END:variables
}
